from twisted.protocols.basic import LineOnlyReceiver, StatefulStringProtocol
from twisted.python import log
from string import ascii_letters as letters
from twisted.internet import defer
import json
import commands

class CasterProtocol(LineOnlyReceiver):
    ''' Protocol to communicate with connected players '''

    def __init__(self):
        self.login = None
        self.creature = None
        self.committed = False
        self.loc_id = None

    def connectionMade (self):
        pass
        #self.sendLine('{"version":0.1}')
        
    def lineReceived (self, line):
        print "received:",line
        commands.do(self, line)

    def connectionLost (self, reason):
        # TODO: Issue disappear request
        pl=self.factory.players
        if self.login in pl:
            del pl[self.login]
        self.disconnect()

    def disconnect(self, reason=None):
        if self.transport.connected:
            if reason:
                self.sendLine(json.dumps([{"what":"fail","msg":reason}]))
            self.transport.loseConnection()
        
    def __str__(self):
        try:
            ip = self.transport.getPeer()
        except:
            ip = "None"
        return 'Protocol<{0}:{1}>'.format(self.login, ip)
    
    def __repr__(self):
        return self.__str__()
